use std::time::Duration;

use base_data::channel::CommandMsg;
use tools::{ResultEx, ResultNull};
use tracing::{debug, error};

use crate::sip2::{
	dialog::{dialog::Dialog, sipdata::SipData, LONG_TIME},
	SipDirection, SipMethod,
};

use super::{SipTimeOver, SipTransaction, SipTransactionState};

pub fn start_tran(dialog: &mut Dialog) {
	//这里可以通过over_time的值控制通话时间....不过最好还是在dialog中控制.
	dialog.over_time = SipTimeOver::CallOvertime(LONG_TIME);
	dialog.retry_time = Duration::ZERO;
	dialog.set_tran_state(SipTransactionState::Proceeding);
}
///处理事务收到的传输层的消息
pub fn handle_tran_msg(dialog: &mut Dialog, sip_data: SipData) -> ResultNull {
	match sip_data.direction {
		SipDirection::Request(m) => match m {
			//这里接收的应该是reinvite事件了.因为第一次sdp由创建dialog时一起创建rtp包.
			//所以这里需要重新生成sdp.
			SipMethod::Invite => {
				dialog.set_sdp(&sip_data.body)?;
				dialog.sip_data = sip_data;
				dialog.tran_handler = SipTransaction::InviteServer;
			}
			SipMethod::Bye | SipMethod::Update => {
				dialog.sip_data = sip_data;
				dialog.tran_handler = SipTransaction::NonInviteServer;
			}
			_ => debug!("no_tran 收到未处理的请求消息..{sip_data:?}"),
		},
		SipDirection::Response(_) => debug!("no_tran 收到无效的回应消息..{sip_data:?}"),
	}
	Ok(())
}
///处理事务收到的命令消息
pub fn handle_command_msg(dialog: &mut Dialog, cmd_msg: CommandMsg) -> ResultNull {
	match cmd_msg {
		CommandMsg::KillChannel(_) | CommandMsg::HangupChannel(_, _) => {
			dialog.generate_new_bye();
			dialog.tran_handler = SipTransaction::NonInviteClient;
		}

		_ => error!("no_tran 收到无效的命令.msg:{cmd_msg:?}"),
	}
	Ok(())
}

///处理事务结束的操作..
/// 这里的参数借用SipTimeControl.Finish:正常结束.Overtime:超时结束..其他都是存在异常的结束
/// 返回true表示是否发送结束dialog消息.
pub fn end_tran(dialog: &mut Dialog) -> ResultEx<bool> {
	//只有超时才会走到这里
	dialog.last_send_bytes = None;
	Ok(true)
}

pub fn handle_time_over(dialog: &mut Dialog, _to: SipTimeOver) -> ResultNull {
	dialog.set_tran_state(SipTransactionState::Terminated);

	Ok(())
}
